import React, {
  forwardRef,
  PropsWithChildren,
  ReactNode,
  useEffect,
  useRef,
  useState,
} from "react";
import styled from "./index.module.less";
import { createPortal } from "react-dom";
import cls from "classnames";

interface IModalProps extends PropsWithChildren {
  title?: string;
  open?: boolean;
  width?: number;
  footer?: ReactNode;
  confirmText?: string;
  closeText?: string;
  classNames?: string;
  contentClassNames?: string;
  wrapClassNames?: string;
  styles?: React.CSSProperties;
  closeable?: boolean;
  closeIcon?: ReactNode;
  mask?: boolean;
  maskClosable?: boolean;
  zIndex?: number;
  loading?: boolean;
  confirmLoading?: boolean;
  ref?: React.Ref<any>;
  onClose?: () => void;
  onConfirm?: () => void;
  afterClose?: () => void;
}

export const Modal = forwardRef((props: IModalProps) => {
  const {
    ref,
    children,
    title,
    open,
    width = 600,
    footer,
    confirmText,
    closeText,
    classNames,
    contentClassNames,
    wrapClassNames,
    styles,
    closeable = true,
    closeIcon,
    mask = true,
    maskClosable = true,
    zIndex = 99,
    loading = false,
    confirmLoading = false,
    onClose,
    onConfirm,
    afterClose,
  } = props;

  const [init, setInit] = useState(true);
  const wrapperRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (open) {
      setInit(false);
    }
    if (!init && open === false) {
      afterClose?.();
    }
  }, [open, init]);

  // 只有confirmLoading为false时才响应关闭事件
  const handleClose = () => {
    if (!confirmLoading) {
      onClose?.();
    }
  };

  const onMaskClick = (e: React.MouseEvent) => {
    if (e.target === wrapperRef.current && maskClosable) {
      handleClose();
    }
  };

  return (
    <>
      {open &&
        createPortal(
          <div
            className={cls(styled["modal-wrapper"], wrapClassNames)}
            style={{
              backgroundColor: mask
                ? "rgba(140, 140, 140, 0.5)"
                : "transparent",
              zIndex,
            }}
            ref={wrapperRef}
            onClick={onMaskClick}
          >
            {/* 弹窗整体 */}
            <div
              className={`modal ${classNames}`}
              style={{
                transform: `translateX(-${width / 2}px)`,
                width,
                ...styles,
              }}
              ref={ref}
            >
              {/* title */}
              <div className="title">
                <div className="title-text">{title}</div>
                {closeable && (
                  <div className="close-btn" onClick={handleClose}>
                    {closeIcon || "x"}
                  </div>
                )}
              </div>
              {/* 弹窗内容 */}
              <div className={cls("content", contentClassNames)}>
                {loading ? "Loading...." : children}
              </div>
              {/* 底部按钮 */}
              {!loading && footer !== null && (
                <>
                  {!footer && (
                    <div className="footer">
                      <div className="btn" onClick={handleClose}>
                        {closeText || "取消"}
                      </div>
                      <div className="primary-btn confirm" onClick={onConfirm}>
                        {confirmLoading && "Loading..."}
                        {!confirmLoading && (confirmText || "确认")}
                      </div>
                    </div>
                  )}
                  {footer && <div>{footer}</div>}
                </>
              )}
            </div>
          </div>,
          document.getElementById("root")!
        )}
    </>
  );
});
